<?php

class Deal_Model extends CI_Model {
	
	/*
	 * Search products
	 * Parameters:
	 * - is_hot: int
	 * - status: int
	 * 
	 * Order by : array
	 */
	function searchProducts($options = array()){
		$this->load->database();
		$this->db->from('products p');
		$this->db->join('productimages pimg', 'p.id = pimg.product_id');
		
		if(!empty($options['category_id'])){
			$this->db->join('category_products cat_pro', 'p.id = cat_pro.product_id AND cat_pro.category_id = '. $options['category_id']);	
		}
		
		$this->addCondition($options);		
		
		//select		
		$this->db->select("p.*, pimg.image_path");
		
		//order by
		if(is_array($options['orderby']) && count($options['orderby']) > 0){
			foreach($options['orderby'] as $key => $value){
				$this->db->order_by($key, $value);	
			}			
		}
		
		if(!empty($options['limit'])){
			if(!empty($options['offset'])){
				$this->db->limit($options['limit'], $options['offset']);
			}else{
				$this->db->limit($options['limit']);
			}
		}
		
		$query = $this->db->get();
		$rs = array();	
		if($query->num_rows() > 0) {
			$rs = $query->result();	
		}
		return $rs;
	}
	
	function countSearchProducts($options = array()){
		$this->load->database();
		$this->db->from('products p');
		if(!empty($options['category_id'])){
			$this->db->join('category_products cat_pro', 'p.id = cat_pro.product_id AND cat_pro.category_id = '. $options['category_id']);	
		}
		return $this->db->count_all_results();
	}
	
	function addCondition($options){
		if(isset($options['is_hot'])) $this->db->where('p.is_hot', 1);
		if(isset($options['status'])) $this->db->where('p.status', 1);
		
		
		
		if(isset($options['search_product_name'])){
			$this->db->or_like(array('title' => $options['search_product_name'], 'product_sku' => $options['search_product_name'])); 			
			//$this->db->where('p.status', 1);
		} 	
	}
	/*
	 * Options param
	 * - active 
	 */
	function getProductCategoriesList($options = array()){
		$this->db->from('categories cat');
		$this->db->join('category_products catpro', 'cat.id = catpro.category_id and catpro.status = 1');
		
		if(!empty($options['status'])) $this->db->where('cat.status', 1);		
		$this->db->select("cat.id, cat.name, COUNT(catpro.category_id) num_of_products");
		$this->db->group_by("cat.id");
		$this->db->order_by("ordering", "asc");
		
		$query = $this->db->get();
		$rs = array();	
		if($query->num_rows() > 0) {
			$rs = $query->result();	
		}
	
		return $rs;
	}
}